<template>
	<div id="DDI_view">
		<el-container>
			<el-header style="margin-bottom: 2%;">
				<h1 class="colorful-title">ComNet: Drug-drug Side Effect</h1>
			</el-header>
			<div class="header-margin"></div>
			<el-main>
				<el-form :model="form" ref="form" label-width="120px">
					<el-form-item label="Drug A" prop="smile1">
						<el-input v-model="form.smile1" placeholder="Enter first SMILE string" @input="validateSmile('smile1')"></el-input>
						<span v-if="!isSmile1Valid" class="error-message">输入不合法，请检查格式</span>
					</el-form-item>
					<el-form-item label="Drug B" prop="smile2">
						<el-input v-model="form.smile2" placeholder="Enter second SMILE string" @input="validateSmile('smile2')"></el-input>
						<span v-if="!isSmile2Valid" class="error-message">输入不合法，请检查格式</span>
					</el-form-item>
					<el-form-item>
						<el-checkbox v-model="show2DStructure">Show 2D Structure of SMILEs</el-checkbox>
					</el-form-item>
					<el-form-item>
						<el-button @click="fillExample" type="info" round>Fill Example</el-button>
						<el-button type="primary" round @click="submitForm" :disabled="!isFormValid">Get Interactions</el-button>
						<el-button @click="clearForm" round>Clear</el-button>
					</el-form-item>
				</el-form>
				<div v-if="loading" class="loading">
					<span>Loading, please wait...</span>
				</div>

				<div v-if="show2DStructure && isFormValid && isSmile1Valid && isSmile2Valid" class="smile-structure">
					<el-row :gutter="20" type="flex" justify="space-between">
						<el-col :span="11">
							<div v-if="form.smile1">
								<h4>Drug A:</h4>
								<div v-html="generate2DImage(form.smile1)"></div>
							</div>
						</el-col>
						<el-col :span="11">
							<div v-if="form.smile2">
								<h4>Drug B:</h4>
								<div v-html="generate2DImage(form.smile2)"></div>
							</div>
						</el-col>
					</el-row>
				</div>
<div v-if="responseData && Object.keys(responseData).length">
  <div class="cards-container">
    <div v-for="(results, typeId) in responseData" :key="typeId">
      <el-card v-for="(result, index) in results" :key="`${typeId}-${index}`" class="result-card">
        <!-- 第一行：预测概率 -->
        <div class="prediction" style="display: flex; justify-content: space-between; align-items: center;">
          <div class="buttons" style="flex: 1; text-align: left;">
            <!-- 如果预测概率>=0.9:danger; 如果0.5<预测概率<0.9 moderate; 如果0.4<概率<=0.5则为 minor -->
            <el-tag v-if="result.predict >= 0.9" type="danger" plain>Danger</el-tag>
            <el-tag v-else-if="result.predict > 0.5 && result.predict < 0.9" type="warning" plain>Moderate</el-tag>
            <el-tag v-else-if="result.predict > 0.4 && result.predict <= 0.5" type="success"  plain>Minor</el-tag>
          </div>
          <div class="tag" style="text-align: right;">
            <el-tag type="info">Predict: {{ result.predict }}</el-tag>
          </div>
        </div>

        <!-- 第二行：描述 -->
          <div class="description">
              <p>{{ result.description.replace('#Drug2', 'Drug B').replace('#Drug1', 'Drug A') }}</p>
            </div>
      </el-card>
    </div>

    <el-empty v-if="!responseData" description="No interaction data available"></el-empty>
  </div>
</div>
			</el-main>
			<el-footer>
				<small>
					Disclaimer: The predictions generated by this model may not be entirely accurate. Users are strongly encouraged to verify and validate the results
					independently. This information is intended for research purposes only and should not be interpreted as medical advice.
				</small>
			</el-footer>
		</el-container>
	</div>
</template>

<script>
import axios from 'axios';

export default {
	data() {
		return {
			show2DStructure: false,
			form: {
				smile1: '',
				smile2: ''
			},
			loading: false,
			responseData: null,
			isSmile1Valid: true,
			isSmile2Valid: true,
			cache: {}
		};
	},
	computed: {
		isFormValid() {
			return this.form.smile1 !== '' && this.form.smile2 !== '';
		}
	},
	methods: {
		validateSmile(type) {
			const smile = this.form[type];
			if (typeof RDKitModule !== 'undefined') {
				try {
					const mol = RDKitModule.get_mol(smile);
					if (type === 'smile1') {
						this.isSmile1Valid = mol !== null;
					} else if (type === 'smile2') {
						this.isSmile2Valid = mol !== null;
					}
					if (!mol) {
						this.$message.error(`输入的${type}字符串不合法，请重新输入`);
					}
				} catch (error) {
					if (type === 'smile1') {
						this.isSmile1Valid = false;
					} else if (type === 'smile2') {
						this.isSmile2Valid = false;
					}
					this.$message.error('验证SMILE字符串时出错: ' + error);
				}
			} else {
				console.error('RDKit.js尚未加载');
				if (type === 'smile1') {
					this.isSmile1Valid = false;
				} else if (type === 'smile2') {
					this.isSmile2Valid = false;
				}
			}
		},
		generate2DImage(smile) {
			if (typeof RDKitModule === 'undefined') {
				console.error('RDKit.js尚未加载');
				return '';
			}
			try {
				const mol = RDKitModule.get_mol(smile);
				if (!mol) {
					this.$message.error('输入的SMILE字符串不合法，请重新输入');
					return '';
				}
				const svg = mol.get_svg();
				mol.delete();
				return svg;
			} catch (error) {
				this.$message.error('生成2D结构图时出错: ' + error);
				return '';
			}
		},
		submitForm() {
			if (this.isFormValid && this.isSmile1Valid && this.isSmile2Valid) {
				this.loading = true;

				// 设置前端缓存的key
				const cacheKey = `${this.form.smile1}-${this.form.smile2}`;
				const cachedData = this.cache[cacheKey];

				if (cachedData) {
					// 如果缓存中有数据，直接使用缓存的数据
					this.responseData = cachedData;
					console.log('使用缓存的数据:', this.responseData);
					this.loading = false;
				} else {
					// 如果没有缓存数据，则发送请求
					axios
						.post('/api/ddi', {
							smile1: this.form.smile1,
							smile2: this.form.smile2
						})
						.then((response) => {
							this.responseData = response.data;

							// 将响应数据缓存到实例的缓存对象中
							this.$set(this.cache, cacheKey, this.responseData);
						})
						.catch((error) => {
							this.$message.error('Error occurred while fetching interaction data');
						})
						.finally(() => {
							this.loading = false;
						});
				}
			}
		},
		clearForm() {
			this.form.smile1 = '';
			this.form.smile2 = '';
			this.responseData = null;
			this.isSmile1Valid = true;
			this.isSmile2Valid = true;
		},
		fillExample() {
			this.form.smile1 = 'CCCC1=NN(C)C2=C1N=C(NC2=O)C1=CC(=CC=C1OCC)S(=O)(=O)N1CCN(C)CC1';
			this.form.smile2 = 'C[C@@H](C1=NC=NC=C1F)[C@](O)(CN1C=NC=N1)C1=C(F)C=C(F)C=C1';
			this.isSmile1Valid = true;
			this.isSmile2Valid = true;
		}
	}
};
</script>

<style scoped>
#DDI_view {
	text-align: center;
	max-width: 60%;
	margin: 8% auto;
}
.loading {
	margin-top: 20px;
	display: flex;
	align-items: center;
	justify-content: center;
}
.colorful-title {
	font-size: 2em;
	font-weight: bold;
	background: linear-gradient(90deg, #ff6b6b, #ff9f43, #feca57, #1dd1a1, #54a0ff, #5f27cd);
	-webkit-background-clip: text;
	-webkit-text-fill-color: transparent;
	display: inline-block;
}
.header-margin {
	margin-top: 20px;
}
.smile-structure {
	margin-top: 20px;
}
.error-message {
	color: red;
	font-size: 0.9em;
}
.smile-structure img {
	max-width: 100%;
	height: auto;
	border: 1px solid #ccc;
	padding: 10px;
	background: #fff;
}
.cards-container {
  display: flex;
  flex-direction: column; /* 每行一个 */
  align-items: center; /* 水平居中 */
  justify-content: center; /* 垂直居中 */
  gap: 20px;
}


.result-card {
	width: 830px;
	margin: 5px 60px;
}

.prediction {
	text-align: right;
	margin-bottom: 5px;
}

.description p {
	font-size: 16px;
	line-height: 1.5;
}
</style>
